package com.dcbeida.activity.store;


import android.app.Activity;
import android.content.DialogInterface;
import android.support.annotation.Nullable;

import com.dcbeida.bean.DrugInfo;
import com.dcbeida.bean.DrugInfoList;
import com.dcbeida.bean.PatientList;
import com.dcbeida.bean.Result_Api;
import com.dcbeida.bean.SourceList;
import com.dcbeida.callback.DialogCallback;
import com.dcbeida.model.StoreModel;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Response;

/**
 * Created by hp on 2016/5/12.
 */
public class StorePresenter implements StoreContract.Present {


    private StoreContract.View view;


    private Activity act;

    private List<DrugInfo> drugInfoList;

    private StoreModel model;

    public StorePresenter(StoreContract.View view, Activity act) {
        //我这里直接把activity作为view，所以不需要
        //mView.setPresenter(this);
        this.view = view;
        this.act = act;
        drugInfoList = new ArrayList<>();
        model = StoreModel.newInstance();

    }


    @Override
    public void start() {

    }

    //取消dialog 取消请求
    DialogInterface.OnCancelListener lis = new DialogInterface.OnCancelListener() {
        @Override
        public void onCancel(DialogInterface dialog) {
            model.getCancel();
        }
    };


    int quantity;

    @Override
    public void addstockindrugcodes(String drugcode) {
        model.addstockindrugcodes(drugcode, new GetdrugcodeCallBack(act, DrugInfoList.class, lis));
    }

    @Override
    public boolean isDrugInfoList() {
        if (drugInfoList.size() > 0) {
            return true;
        }
        return false;
    }

    /**
     * from			    来货单位
     * fromID			来货单位ID
     * invoiceMoney		金额
     * deliverImgUrl	送货单（拍照）
     */
    @Override
    public void addstockinlog(String from,int fromID,String invoiceMoney,String deliverImgUrl) {
        if (view.getRkDate() == null || view.getRkDate().trim().length() == 0) {
            view.showTip("入库时间不正确");
            return;
        }

        if (view.getFhDate().length() == 0) {
            view.showTip("请选择发货时间");
            return;
        }

        String drugcodes = "";
        int quantity = 0;
        for (DrugInfo info : drugInfoList) {
            quantity += info.getQuantity();
            if (drugcodes.length() != 0) {
                drugcodes += ",";
            }
            drugcodes += info.getDrugcode();
        }

        model.addstockinlog(from, fromID, invoiceMoney, deliverImgUrl, drugcodes, view.getRkDate().trim(), view.getFhDate(), quantity, new ApiCallBack(act, Result_Api.class, lis));
    }


    //根据条形码查询详细信息
    class GetdrugcodeCallBack<T> extends DialogCallback<T> {

        public GetdrugcodeCallBack(Activity activity, Type type, DialogInterface.OnCancelListener listener) {
            super(activity, type, listener);
        }

        @Override
        public void onResponse(T data) {
            if (data != null) {
                if (data instanceof DrugInfoList) {
                    if (((DrugInfoList) data).getList().size() > 0) {
                        DrugInfo info = ((DrugInfoList) data).getList().get(0);
                        if (drugInfoList.contains(info)) {
                            view.showTip("此款药品已存在列表中...");
                            return;
                        }


                        int pos = -1;
                        int head_pos = 0;
                        for (int i = 0; i < drugInfoList.size(); i++) {
                            if (drugInfoList.get(i).getDrugid() == info.getDrugid()) {
                                if (drugInfoList.get(i).isFirst()) {
                                    head_pos = i;
                                }
                                pos = i;
                            }
                        }

                        if (pos == -1) {
                            info.setFirst(true);
                            info.setCount(info.getQuantity());
                            pos = drugInfoList.size();
                            head_pos = pos;
                        } else {
                            info.setFirst(false);
                            DrugInfo headInfo = drugInfoList.get(head_pos);
                            int count = headInfo.getCount() + info.getQuantity();
                            headInfo.setCount(count);
                            pos = pos + 1;
                            //additem(pos,data);
                        }

                        drugInfoList.add(pos, info);
                        //iew.addItem((DrugInfo) data);
                        view.addItem(pos, info, head_pos, drugInfoList.get(head_pos));



//                        quantity += info.getQuantity();
//                        drugInfoList.add(info);
//                        view.addItem(info);
//                        view.setQuantity(drugInfoList.size(), quantity);



                    } else {
                        view.showTip("没有查询到此药品");
                    }

                }
            } else {
                view.showTip("没有查询到此药品");
            }
        }


        public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) {
            super.onError(call, response, e);
            view.showTip("数据未请求成功,请检查网络...");


        }
    }


    //药店销售-查询患者信息列表
    class QuerypatientCallBack<T> extends DialogCallback<T> {

        public QuerypatientCallBack(Activity activity, Type type, DialogInterface.OnCancelListener listener) {
            super(activity, type, listener);
        }

        @Override
        public void onResponse(T data) {
            if (data != null) {
                if (data instanceof PatientList) {
                    if (((PatientList) data).getList().size() > 0) {

                    }
                }
            }
        }

        public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) {
            super.onError(call, response, e);
            view.showTip("数据未请求成功,请检查网络...");


        }
    }


    //药店销售-新增销售记录 返回结果
    class ApiCallBack<T> extends DialogCallback<T> {

        public ApiCallBack(Activity activity, Class<T> tclass, DialogInterface.OnCancelListener listener) {
            super(activity, tclass, listener);
        }

        @Override
        public void onResponse(T data) {
            if (data != null) {
                if (((Result_Api) data).getCode() == 1) {
                    view.showTip(((Result_Api) data).getMsg());
                    view.confimSuccess();
                }
            }
        }


        public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) {
            super.onError(call, response, e);
            //view.showTip("数据未请求成功,请检查网络...");

        }
    }


    @Override
    public void getSourcelInfo(String keyword) {
        model.getSourcelInfo(keyword, new StorePresenter.GetSourceInfoCallBack(act, SourceList.class, lis));
    }

    class GetSourceInfoCallBack<T> extends DialogCallback<T> {

        public GetSourceInfoCallBack(Activity activity, Type type, DialogInterface.OnCancelListener listener) {
            super(activity, type, listener);
        }

        @Override
        public void onResponse(T data) {
            if (data != null) {
                if (((SourceList) data).getList().size() >= 0) {
                    view.showList(((SourceList) data).getList());
                }
            } else {
                view.showList(null);
            }
        }


        public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) {
            super.onError(call, response, e);
            view.showList(null);

        }
    }

}
